package com.ytzq.base.helper;

import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 * 字符串处理帮助类
 * @author 门士松  20130822
 * @version 1.1
 * @since
 */
public class StringHelper{
	/**
	 * 验证是null或长度为0
	 */
	public static boolean isEmpty(String str) {
		return (str==null || str.trim().length()<1);
	}
	/**
	 * 将null转换为""
	 */
	public static String ensure(String str){
		return str==null?"":str;
	}
	/**
	 * 判断是否为数字
	 * @param str
	 */
	public static boolean isNumber(String str){
		Pattern pattern=java.util.regex.Pattern.compile("[0-9]*"); 
        Matcher match=pattern.matcher(str);
        return match.matches();
	}
	/**
	 * md5加密
	 * @param input
	 * @return md5加密后
	 */
	public static String getMD5(String input) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] messageDigest = md.digest(input.getBytes());
			BigInteger number = new BigInteger(1, messageDigest);
			String hashtext = number.toString(16);
			// Now we need to zero pad it if you actually want the full 32 chars.
			while (hashtext.length() < 32) {
				hashtext = "0" + hashtext;
			}
			return hashtext;
		}catch (NoSuchAlgorithmException e) {
			throw new RuntimeException(e);
		}
	}
	/**
	 * 根据密匙进行DES加密
	 * @param key 密匙
	 * @param info 要加密的信息
	 * @return String 加密后的信息
	 * @throws NoSuchPaddingException 
	 * @throws NoSuchAlgorithmException 
	 * @throws InvalidKeyException 
	 * @throws BadPaddingException 
	 * @throws IllegalBlockSizeException 
	 */
	public static String encryptToDES(SecretKey key, String info) throws Exception {
		// 定义 加密算法,可用 DES,DESede,Blowfish
		String Algorithm = "DES";
		// 加密随机数生成器 (RNG),(可以不写)
		SecureRandom sr = new SecureRandom();
		// 定义要生成的密文
		byte[] cipherByte = null;
		// 得到加密/解密器
		Cipher c1 = Cipher.getInstance(Algorithm);
		// 用指定的密钥和模式初始化Cipher对象
		// 参数:(ENCRYPT_MODE, DECRYPT_MODE, WRAP_MODE,UNWRAP_MODE)
		c1.init(Cipher.ENCRYPT_MODE, key, sr);
		// 对要加密的内容进行编码处理,
		cipherByte = c1.doFinal(info.getBytes());
		// 返回密文的十六进制形式
		return byte2hex(cipherByte);
	}
	/**
	 * 根据密匙进行DES加密(默认静态密钥)
	 * @param stringKey 密匙,长度为8位的字符串
	 * @param info 要加密的信息
	 * @return String 加密后的信息
	 * @throws Exception 
	 */
	public static String encryptToDES(String info,String stringKey) throws Exception {
		byte[] PWD = stringKey.getBytes();
		SecretKey key = new SecretKeySpec(PWD, "DES"); 
		return StringHelper.encryptToDES(key, info);
	}
	/**
	 * 根据密匙进行DES解密
	 * @param key 密匙
	 * @param info 要解密的密文
	 * @return String 返回解密后信息
	 */
	public static String decryptByDES(SecretKey key, String info) throws Exception {
		// 定义 加密算法,
		String Algorithm = "DES";
		// 加密随机数生成器 (RNG)
		SecureRandom sr = new SecureRandom();
		byte[] cipherByte = null;
		// 得到加密/解密器
		Cipher c1 = Cipher.getInstance(Algorithm);
		// 用指定的密钥和模式初始化Cipher对象
		c1.init(Cipher.DECRYPT_MODE, key, sr);
		// 对要解密的内容进行编码处理
		cipherByte = c1.doFinal(hex2byte(info));
		// return byte2hex(cipherByte);
		return new String(cipherByte);
	}
	/**
	 * 根据密匙进行DES解密(默认密钥)
	 * @param info 要解密的密文
	 * @param stringKey 密匙,长度为8位的字符串
	 * @return String 返回解密后信息
	 * @throws Exception 
	 */
	public static String decryptByDES(String info,String stringKey) throws Exception {
		byte[] PWD = stringKey.getBytes();
		SecretKey key = new SecretKeySpec(PWD, "DES"); 
		return StringHelper.decryptByDES(key, info);
	}	
    /** 
     * 将二进制转化为16进制字符串 
     * @param b 二进制字节数组 
     * @return String 
     */  
	public static String byte2hex(byte[] b) {  
        String hs = "";  
        String stmp = "";  
        for (int n = 0; n < b.length; n++) {  
            stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));  
            if (stmp.length() == 1) {  
                hs = hs + "0" + stmp;  
            } else {  
                hs = hs + stmp;  
            }  
        }  
        String str = hs.toUpperCase(Locale.US);
        return str;  
    }  
    /** 
     * 十六进制字符串转化为2进制 
     * @param hex 
     * @return 
     */  
    public static byte[] hex2byte(String hex) {  
        byte[] ret = new byte[8];  
        byte[] tmp = hex.getBytes();  
        for (int i = 0; i < 8; i++) {  
            ret[i] = uniteBytes(tmp[i * 2], tmp[i * 2 + 1]);  
        }  
        return ret;  
    }  
    /** 
     * 将两个ASCII字符合成一个字节； 如："EF"--> 0xEF 
     * @param src0  byte 
     * @param src1  byte 
     * @return byte 
     */  
    public static byte uniteBytes(byte src0, byte src1) {  
        byte _b0 = Byte.decode("0x" + new String(new byte[] { src0 })).byteValue();  
        _b0 = (byte) (_b0 << 4);  
        byte _b1 = Byte.decode("0x" + new String(new byte[] { src1 })).byteValue();  
        byte ret = (byte) (_b0 ^ _b1);  
        return ret;  
    }
}
